<template>
    <div class="info-attr-module">

        <div class="title">赛事报名</div>
        <div class="register">


            <div class="item">
                <div class="name">比赛时间</div>
                <div class="right">
                    <div class="text">{{matchinfo.matchdate}}</div>
                </div>
            </div>
            <div class="item">
                <div class="name">赛事名称</div>
                <div class="right">
                    <div class="text">{{matchinfo.match_name}}</div>

                </div>
            </div>
            <div class="item">
                <div class="name">赛项类别</div>
                <div class="right">
                    <div class="text">{{itemInfo.item_name}}</div>
                </div>
            </div>
            <div class="item">
                <div class="name">报名时间</div>
                <div class="right">
                    <div class="text">{{matchinfo.signdate}}</div>
                </div>
            </div>
            <div class="item">
                <div class="name">赛项类型</div>
                <div class="right">
                    <div class="text">{{itemInfo.typename}}</div>
                </div>
            </div>
            <div class="item">
                <div class="name"><span>*</span>*参赛组别</div>
                <div class="right">
                  <el-radio-group v-model="ruleForm.groupId">
                    <el-radio v-for="(item,index) in dictGroups.items" :key="index" :label="item.id">{{item.dictLabel}}</el-radio>

                  </el-radio-group>
                </div>
            </div>
            <div class="item">
                <div class="name"><span>*</span>队伍名称</div>
                <div class="right">
                    <input  v-model="ruleForm.teamName" placeholder="请输入队伍名称">
                </div>
            </div>
            <div class="item">
                <div class="name"><span>*</span>指导老师</div>
                <div class="right">
                    <div class="select" @click="toSelect('teacher',teacher)">
                        <div class="text">{{teacher.real_name}}</div>
                      <div class="text" v-if="!teacher.real_name"> 请选择</div>
                        <el-icon color="#959CA9" v-if="!teacher.real_name">

                            <ArrowRight />
                        </el-icon>
                    </div>
                </div>
            </div>
        </div>
        <div class="title">赛事报名</div>
        <div class="register">
            <div class="item" v-for="(item,index) in userList"  :key="index"  @click="toSelect('student',item)">
                <div class="name"  ><span>*</span>队员{{index+1}}</div>
                <div class="right">
                    <div class="text">{{item.real_name}}</div>
                </div>
            </div>
          <div class="add" @click="addUser">
            <el-icon color="#00A0E9">
              <CirclePlusFilled />
            </el-icon>添加队员
          </div>
          <div class="add" @click="deleteUser" v-show="userList.length>1">
            <el-icon color="#00A0E9">
              <CloseBold />
            </el-icon>删除队员
          </div>

        </div>


        <div class="info-hint">
            <span>注：</span>
            <div>赛前请关注 参赛报名 > 报名记录 > 对应赛事赛项的参赛时间信息</div>
        </div>
        <div class="registe_agreement"><el-checkbox v-model="ruleForm.checked2" />点击同意并接受即表示您已阅读了解并同意<el-button
                @click="handleaGreement" type="text">《注册协议》</el-button></div>

        <div class="fixed-btn">
            <div class="btn" @click="submit">提交报名</div>
        </div>
    </div>

  <drawerSelect ref="dsRef" :title="'请选择'">
    <div class="drawer-select">
      <div v-for="(item,index) in currentSelect.items" v-show="item.selected!==1||item.id == currentInput.id " :key="index" class="item" @click="handleSelect(item.id,item.real_name)"
           :class="item.id===currentInput.id|| teacher.values.indexOf(item.id)!==-1?'active':''">
        {{item.real_name}} <el-icon color="#00A0E9"><Select /></el-icon>
      </div>
    </div>
  </drawerSelect>
</template>

<script lang="ts" setup>
import { defineComponent, reactive, ref } from "vue";
import {useRoute, useRouter} from "vue-router";
import drawerSelect from "@/components/DrawerSelect";
import baseService from "@/service/baseService";
import {ElMessage} from "element-plus";
import {getCache} from "@/utils/cache";
let router = useRouter();
const route = useRoute();
const dsRef = ref();
let info =ref({
  haveJinJi:false,
  team:getCache( "CacheToken",{ isSessionStorage: true }, {})['spTeamEntity']
});
const  id = route.query.id ;
let matchId :any= route.query.matchId;
const season= route.query.season;
const dictGroups =ref({items:[]});
const selectGroup= ref({student:{title:'选择选手',items:[{code:'1',name:'选手1'},{code:'2',name:'选手2'}],value:'1'},teacher:{title:'选择老师',items:[]}});
const currentSelect:any = ref(selectGroup.value['student']);
let matchinfo = ref({});
let matchiteminfo = { student_num:3,
  student_num_max:5,
  teacher_num:1,
  teacher_num_max:3,
  classname: "",
  item_name: ""};
const ruleForm = reactive({
  users:[],
  matchItemId:id,
  teamName: "",
  checked2:false,
  groupId: null
});
const teacher:any = ref({values:[]});
const currentInput:any=ref();
let selectType='student';
const toSelect=(type:string ,c:any)=>{
  selectType=type;
  if(type=='student'){

    currentSelect.value = selectGroup.value[type];
    currentSelect.value.title='请选择选手';
  }
  if(type=='teacher'){
    currentSelect.value = selectGroup.value[type];
  }
  currentInput.value= c;
  dsRef.value.open();
}

const handleSelect = (v:any,n:any,type:string) => {
  currentInput.value.id =v;
  currentInput.value.real_name =n;
  if(selectType==='student'){
    currentSelect.value.items.forEach((e:any)=>{
      e.selected=2;
      userList.value.forEach((e2:any)=>{
        if(e2.id ==e.id ){
          e.selected=1;
        }
      })
    });
  }else if (selectType==='teacher'){
    currentInput.value.id =null;
    currentSelect.value.items.forEach((e:any)=>{
      if(e.id ===v){
        e.selected=e.selected===3?2:3;
      }
    });
    let selectId: any[]=[];
    let selectName: any[]=[];
    currentSelect.value.items.forEach((e:any)=>{
      if(e.selected ===3){
        selectId.push(e.id);
        selectName.push(e.real_name);
      }
    });
    teacher.value.values = selectId;
    teacher.value.real_name =selectName.join(",");
  }
}

/**
 *赛项
 */
const itemInfo = ref({
  "base_match_item_id": "43",
  "classname": "旋翼类",
  "student_num_max": 1,
  "item_type": 100201,
  "match_id": "1",
  "item_classify": "100101",
  "teacher_num": 1,
  "item_name": "飞跃巅峰赛",
  "id": "148",
  "student_num": 1,
  "typename": "个人赛",
  "teacher_num_max": 1
});
const userList :any=ref([{
  id:null,
  name:null,
  teacher:{}
}]);
const handleaGreement = () => {
    router.push("/auth/agreement");
}

const addUser=()=>{
  userList.value.push({teacher:{}});
}
const deleteUser=()=>{
  userList.value.pop();
}

baseService.get("/front/spbasematchitemgoupref/queryGroup?id="+route.query.id).then((e:any)=>{
  if(e.code=='0'){
    dictGroups.value.items = e.data;
  }
});

const queryUser =(season:string)=>{
  baseService.get("/front/fast/user/userList/list?pageSize=10&type=4&season="+season+"&noItemId="+id).then((e:any)=>{
    if(e.code=='0'){
      console.log(e.data);
      selectGroup.value['student'].items= e.data;
    }
  });
}

baseService.get("/front/fast/user/userList/list?pageSize=10&type=3").then((e:any)=>{
  if(e.code=='0'){
    selectGroup.value['teacher'].items= e.data;
  }
});

baseService.get("/front/fast/match/match/info?id="+matchId).then((e:any)=>{
  if(e.code=='0'){
    matchinfo.value = e.data;
    queryUser(e.data.season);
  }
});
baseService.get("/front/fast/match/matchItem/info?id="+id).then((e:any)=>{
  if(e.code=='0'){
    matchiteminfo = e.data;

  }
});
/**
*校验信息
*/
const checkSubmit = ()=>{
  if(!ruleForm.teamName){
    ElMessage.error("请填写队伍名称！");
    return false
  }else if(ruleForm.teamName.length>30){
    ElMessage.error("队伍名称不能超过30个字！");
    return false;
  }
  if(!ruleForm.groupId){
    ElMessage.error("请选择参赛组别！");
    return false
  }
  if(teacher.value.values.length ==0){
    ElMessage.error("请选择指导老师！");
    return false
  }
  if(teacher.value.values.length > matchiteminfo.teacher_num_max){
    ElMessage.error("指导老师最多为"+matchiteminfo.teacher_num_max+"位！");
    return false
  }
  if(teacher.value.values.length < matchiteminfo.teacher_num){
    ElMessage.error("指导老师少为"+matchiteminfo.teacher_num+"位！");
    return false
  }
  for(let i =0 ;i<matchiteminfo.student_num ;i++){
    if(!userList.value[i].id){
      ElMessage.error("请选择队员"+(i+1)+"！");
      return false;
    }

  }
  if (!ruleForm.checked2) {
    ElMessage.error("您未同意用户协议，请先同意！");
    return false
  }
  return true;
}
/**
*提交
*/
const  submit =()=>{
  const users:any =[];
  //校验不通过则返回
  if(!checkSubmit()){
    return;
  }
  userList.value.forEach((e:any)=>{
    if(e.id){
      users.push({userId:e.id});
    }
  })
  const dataForm={groupId:ruleForm.groupId,teamName:ruleForm.teamName,users,matchItemId:ruleForm.matchItemId,teachers:teacher.value.values.join(",")};
  baseService.post("/front/spmatchItemTeam/save  ",dataForm).then((res:any )=> {
    if (res.code == 0) {
      ElMessage.success('报名成功');
      router.push("/match/info?id="+matchId);
    }else{
      ElMessage.error(res.msg);
    }
  })


}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
